package cn.com.cifi.mars.web.action.report;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.com.cifi.mars.bean.vo.price.PriceReportVO;
import cn.com.cifi.mars.bean.vo.price.req.PriceReportReqParam;
import cn.com.cifi.mars.common.base.BaseAction;
import cn.com.cifi.mars.common.bean.R;
import cn.com.cifi.mars.constant.VersionTypeEunm;
import cn.com.cifi.mars.entity.DmDmValueReport;
import cn.com.cifi.mars.service.DmDmValueReportService;
import cn.com.cifi.mars.util.DateUtils;
import cn.com.cifi.mars.util.FileUtils;
import cn.com.cifi.mars.util.PriceReportTemplate;
import cn.com.cifi.mars.util.PriceReportUtils;
import cn.com.cifi.mars.util.ReportUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class PriceReportController extends BaseAction implements IPriceReportController {

    private static final String REPORT_NAME_PATTERN = "%s最新全盘货值-截止%s-%s";

    private static final String SHEET_NAME_PATTERN = "%s最新全盘货值-截止%s";
    @Autowired
    private DmDmValueReportService dmDmValueReportService;

    @Override
    public R<List<PriceReportVO>> priceReport(String apiVersion, PriceReportReqParam param) {
        if (StringUtils.isBlank(param.getOrgId())) {
            return fail("orgId不能为空");
        }

        String localEndDate = LocalDate.now().format(DateTimeFormatter.ofPattern(DateUtils.DATE_JFP_STR));
        String endDate = param.getEndDate() == null ? localEndDate : param.getEndDate();

        //查距离截止日期最近的截止日期，因为存在截止日期月在数据库中不存在的可能
        String latestEndDate = dmDmValueReportService.getLatestEndDate(endDate);
        if (latestEndDate == null) {
            return ok(new ArrayList<>(0));
        }

        //根据项目ID与截止年月查询数据
        QueryWrapper<DmDmValueReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("end_date", latestEndDate).eq("project_id", param.getOrgId());
        List<DmDmValueReport> dmDmValueReportList = dmDmValueReportService.list(queryWrapper);
        if (CollectionUtils.isEmpty(dmDmValueReportList)) {
            return ok(dmDmValueReportList);
        }

        //投资版的楼栋名称拼接上经营方式、装修方式、属性标签
        dmDmValueReportList.parallelStream().filter(x -> VersionTypeEunm.INVESTMENT.getKey().equals(x.getVersionType())).forEach(x -> {
            x.setBuildingName(x.getBuildingName() + "(" + x.getBusinessTypeName() + "-" + x.getFreeTypeName() + "-" + x.getProTypeName() + ")");
        });

        //计算货值
        List<PriceReportVO> priceReportVOList = PriceReportUtils.calcPriceReport(dmDmValueReportList);

        //排序
        List<PriceReportVO> sortedList = priceReportVOList.parallelStream().sorted((a, b) -> {
            String aOrgType = a.getOrgType();
            String bOrgType = b.getOrgType();
            if (!aOrgType.equals(bOrgType)) {
                return aOrgType.compareTo(bOrgType);
            }

            String aName = a.getOrgName();
            String bName = b.getOrgName();
            return ReportUtils.compareStrStartedChinaNum(aName, bName);
        }).collect(Collectors.toList());

        return ok(sortedList);
    }


    @Override
    public void priceReportExport(String apiVersion, PriceReportReqParam param, HttpServletResponse httpServletResponse) {
        if (StringUtils.isBlank(param.getOrgId())) {
            return;
        }

        String localEndDate = LocalDate.now().format(DateTimeFormatter.ofPattern(DateUtils.DATE_JFP_STR));
        String endDate = param.getEndDate() == null ? localEndDate : param.getEndDate();

        //根据项目ID与截止年月查询数据
        String latestEndDate = dmDmValueReportService.getLatestEndDate(endDate);
        QueryWrapper<DmDmValueReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("end_date", latestEndDate).eq("project_id", param.getOrgId());
        List<DmDmValueReport> dmDmValueReportList = dmDmValueReportService.list(queryWrapper);
        if (CollectionUtils.isEmpty(dmDmValueReportList)) {
            return;
        }

        //计算货值
        List<PriceReportVO> list = PriceReportUtils.calcPriceReport(dmDmValueReportList);

        //将分组合并为一个Map
        Map<String, Map<String, Object>> resultMap = PriceReportUtils.mergeGroupMap(list, dmDmValueReportList);

        //排序
        List<Map<String, Object>> result = PriceReportUtils.toSortedList(resultMap);

        String endDateNoneSplit = endDate.replace("-", "");
        String reportName = FileUtils.complianceFileName(String.format(REPORT_NAME_PATTERN, dmDmValueReportList.get(0).getProjectName(), endDateNoneSplit, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHH"))));
        String sheetName = FileUtils.complianceFileName(String.format(SHEET_NAME_PATTERN, dmDmValueReportList.get(0).getProjectName(), endDateNoneSplit));
        PriceReportTemplate priceReportTemplate = new PriceReportTemplate();
        priceReportTemplate.appendRows(result);
        priceReportTemplate.setSheetName(sheetName);
        try (OutputStream outputStream = httpServletResponse.getOutputStream()) {
            httpServletResponse.setContentType("application/vnd.ms-excel");
            httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(reportName + ".xls", "utf-8"));
            priceReportTemplate.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

}
